package com.wn.controller;

import com.alibaba.fastjson.JSON;
import com.wn.bean.R;
import com.wn.bean.Student;
import com.wn.service.StudentService;
import com.wn.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yellow Docter
 * @date 2022 -07-01
 * @desc
 */
@WebServlet("/findStuById")
public class FindStuByIdServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");

        // 01 拿到数据
        String id = request.getParameter("id");

        //02 调用service

        StudentService studentService = new StudentServiceImpl();
        Student stu = studentService.findStuById(Integer.parseInt(id));

        //03 回写
        R r = null;
        if (stu != null){
            r = R.ok();
            r.setData(stu);
        }else{
            r = R.error();
        }

        String jsonString = JSON.toJSONString(r);
        response.getWriter().write(jsonString);

    }
}
